import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:szwf/common/BoxPage.dart';
import 'package:szwf/page/comeOut/index.dart';
import 'package:szwf/utils/common_toast.dart';
import 'package:szwf/utils/store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:szwf/utils/dio_http.dart';
class PutPage extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<PutPage> {
  List formList;            //基本信息
  List ckLick;              //仓库号
  List KwhLick;             //库位号
  String numText;
  String _selectTypeKwh;  //库位号
  String _selectTypeCkh;  //仓库号
  String qrNumber;         //二维码编号

  var remark = TextEditingController();
  var remark1 = TextEditingController();
  var remark2 = TextEditingController();

  initState() {
    super.initState();
    getCkh();
    formList = [
      {"title": '车牌号 :',"value":'123'},
    ];
    ckLick = [
      {"title": '一号仓库',"value":'一号仓库'},
    ];

    KwhLick = [
      {"title": '空',"value":'空'},
    ];
  }
  //仓库号
  getCkh () async {
    final prefs = await SharedPreferences.getInstance();
    //getValue default 0
    final counter = prefs.getString('companyId') ?? '999';
    //获取仓库号
    String url = '/wfgl/warehouse/getList';
    var params = {
      "companyId":counter,
    };
    var res = await DioHttp.of(context).post(url,params);
    var resString = json.decode(res.toString());
    var ckh = [];

    for(var item in resString['ret']){
      print(item);
      ckh.add(
        {
          'title':item['name'],
          'value':item['id'].toString()
        }
      );
    }
    setState(() {
      ckLick = ckh;
    });

  }

  //获取库位号
  onKwh (value) async {

    final prefs = await SharedPreferences.getInstance();
    //getValue default 0
    final companyId = prefs.getString('companyId') ?? '999';
    String url = '/wfgl/warehouselocation/getList';
    var params = {
      "companyId":companyId,
      "beenDeleted":0,
      "warehouseId":value
    };
    var res = await DioHttp.of(context).post(url,params);
    var resString = json.decode(res.toString());
    var kwh = [];

    for(var item in resString['ret']){
      print(item);
      kwh.add(
          {
            'title':item['name'],
            'value':item['id'].toString()
          }
      );
    }
    setState(() {
      KwhLick = kwh;
      _selectTypeKwh = null;
    });
  }
  //弹出对话康
  showAlertDialog(BuildContext context) async {

    if(_selectTypeKwh == null ||_selectTypeCkh == null  ){
      CommonToast.showToast('仓库号与库位号为必选!');
      return;
    }else{
      final prefs = await SharedPreferences.getInstance();
      //getValue default 0
      final companyId = prefs.getString('companyId') ?? '999';
      String url = '/wfgl/entrancewarehouse/insertSelective';
      var params = {
        "companyId":companyId,
        "contacts":remark1.text,
        "phone":remark2.text,
        "qrNumber":qrNumber,
        "remark":remark.text,
        "seatNumber":_selectTypeKwh,
        "warehouseNo":_selectTypeCkh,
      };
      var res = await DioHttp.of(context).post(url,params);
      var resString = json.decode(res.toString());
      if(resString['rc'] == 0) {
        print(resString);
        //显示对话框
        showDialog(
            context: context,
            barrierDismissible:false,//是否可以点击背景关闭
            builder: (BuildContext context) {
              return AlertDialog(//设置对话康
                title: Text('保存成功'),
                content: Text('是否继续入库?'),
                actions: <Widget>[
                  FlatButton(
                    child: Text('确定'),
                    onPressed: () {
                      final PageRouteBuilder _comeOutRoute = new PageRouteBuilder(
                        pageBuilder: (BuildContext context, _, __) {
                          return ComeOut();
                        },
                      );
                      Navigator.pushAndRemoveUntil(context, _comeOutRoute, (Route<dynamic> r) => false);
                    },
                  ),
                ],
              );
            }
        );

      }else{
        CommonToast.showToast(resString['err']);
      }
    }




  }

  Widget buildGrid(typePage) {
    List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
//  print(typePage);
  setState(() {
    remark1.text = typePage['qy']['remark1'];
    remark2.text = typePage['qy']['remark2'];
    remark.text = typePage['qc']['remark'];
    formList =  typePage['formList'];
    qrNumber =  typePage['qc']['qrNumber'];
  });
    for(var item in formList) {
      tiles.add(
        Column(
          children: <Widget>[
            Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(item['title'],style: TextStyle(color: Colors.grey[600]),),
                  Expanded(
                    child: Text(item['value'],maxLines: 1,overflow: TextOverflow.ellipsis,textAlign: TextAlign.right,),
                  )
                ]
            ),
            Divider(
              height: 18.0,
              indent: 0.0,
              color: Colors.grey[400],
            ),
          ],
        )
      );
    }
    content = Column(
        children: tiles
    );
    return content;
  }
  //获取仓库号
  List<DropdownMenuItem<String>> ckLickBox() {
    List<DropdownMenuItem<String>> ckLicktiles = [];//先建一个数组用于存放循环生成的widget
    for(var item in ckLick) {
      ckLicktiles.add(
        DropdownMenuItem(
          child: Text(item['title']),
          value: item['value'],
        ),
      );
    }

    return ckLicktiles;
  }
  //获取库位号
  List<DropdownMenuItem<String>> KwhLickBox() {
    List<DropdownMenuItem<String>> KwhLicktiles = [];//先建一个数组用于存放循环生成的widget
    for(var item in KwhLick) {
      KwhLicktiles.add(
        DropdownMenuItem(
          child: Text(item['title']),
          value: item['value'],
        ),
      );
    }

    return KwhLicktiles;
  }
  @override
  Widget build(BuildContext context) {
    Map typePage = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      backgroundColor: Colors.grey[200],
//        key: scaffoldKey,
        appBar: AppBar(
          actions: <Widget>[
            Icon(Icons.add,color: Colors.white,),
            Icon(Icons.add,color: Colors.white,)
          ],
          title: Center(
            child: Text('入库操作'),
          ),
        ),
        body:ListView(
          padding: EdgeInsets.all(10.0),
          children: <Widget>[
            BoxPage(Box:buildGrid(typePage),title: '基本信息',),
            BoxPage(Box:Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 80.0,
                      child: Text('仓库号 :',style: TextStyle(color: Colors.grey[600]),),
                    ),
                    Expanded(
                      child: DropdownButtonHideUnderline(
                          child: new DropdownButton(
                            items: ckLickBox(),
                            hint: new Text('必选',style: TextStyle(fontSize: 12,color: Colors.grey[600]),),
                            onChanged: (value){
                              setState(() {
                                _selectTypeCkh = value;
                              });
                              onKwh(value);
                            },
//              isExpanded: true,
                            value: _selectTypeCkh,
                            elevation: 24,//设置阴影的高度
                            style: TextStyle(//设置文本框里面文字的样式
                              color: Color(0xff4a4a4a),
                              fontSize: 16,

                            ),
//              isDense: false,//减少按钮的高度。默认情况下，此按钮的高度与其菜单项的高度相同。如果isDense为true，则按钮的高度减少约一半。 这个当按钮嵌入添加的容器中时，非常有用
                            iconSize: 40.0,
                          )
                      ),
                    )

                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 80.0,
                      child: Text('库位号 :',style: TextStyle(color: Colors.grey[600]),),
                    ),
                    Expanded(
                      child: DropdownButtonHideUnderline(
                          child: new DropdownButton(
                            items: KwhLickBox(),
                            hint: new Text('必选',style: TextStyle(fontSize: 12,color: Colors.grey[600]),),
                            onChanged: (value){
                              setState(() {
                                _selectTypeKwh = value;
                              });
                            },
//              isExpanded: true,
                            value: _selectTypeKwh,
                            elevation: 24,//设置阴影的高度
                            style: TextStyle(//设置文本框里面文字的样式
                              color: Color(0xff4a4a4a),
                              fontSize: 16,

                            ),
//              isDense: false,//减少按钮的高度。默认情况下，此按钮的高度与其菜单项的高度相同。如果isDense为true，则按钮的高度减少约一半。 这个当按钮嵌入添加的容器中时，非常有用
                            iconSize: 40.0,
                          )
                      ),
                    )

                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 80.0,
                      child: Text('联系人 :',style: TextStyle(color: Colors.grey[600]),),
                    ),
                    Expanded(
                      child: TextField(
                        onChanged: (value){
                          remark1.text=value;
                        },
                        controller: TextEditingController.fromValue(TextEditingValue(
                          // 设置内容
                            text: remark1.text,
                            // 保持光标在最后
                            selection: TextSelection.fromPosition(TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: remark1.text.length))
                        )),
                        autofocus: false,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(
                            fontSize: 12.0
                          ),
                          border: InputBorder.none, // 去掉下滑线
                        ),
                      ),
                    )

                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 80.0,
                      child: Text('联系电话 :',style: TextStyle(color: Colors.grey[600]),),
                    ),
                    Expanded(
                      child: TextField(
                        onChanged: (value){
                          remark2.text=value;
                        },
                        controller: TextEditingController.fromValue(TextEditingValue(
                          // 设置内容
                            text: remark2.text,
                            // 保持光标在最后
                            selection: TextSelection.fromPosition(TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: remark2.text.length))
                        )),
                        autofocus: false,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(
                              fontSize: 12.0
                          ),
                          border: InputBorder.none, // 去掉下滑线
                        ),
                      ),
                    )

                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 80.0,
                      child: Text('备注 :',style: TextStyle(color: Colors.grey[600]),),
                    ),

                    Expanded(
                      child: TextField(
                        onChanged: (value){
                          remark.text=value;
                        },
                        controller: TextEditingController.fromValue(TextEditingValue(
                          // 设置内容
                            text: remark.text,
                            // 保持光标在最后
                            selection: TextSelection.fromPosition(TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: remark.text.length))
                        )),
                        autofocus: false,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(
                              fontSize: 12.0
                          ),
                          border: InputBorder.none, // 去掉下滑线
                        ),
                      ),
                    )

                  ],
                )
              ],
            ),

              title: '入库信息',),
            SizedBox(
              height: 20.0,
            ),
            RaisedButton(
              color: Colors.blue,
              textColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25),
              ),
              onPressed: () {
//                         save();
                showAlertDialog(context);
              },
              child: Text('确定'),
            ),
            SizedBox(
              height: 20.0,
            )

          ],
        )
    );
  }


}


